﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Threading.Tasks;
using XYAC.Framework.MonitorTireMaterialManual.Context;
using XYAC.Framework.MonitorTireMaterialManual.Entities;
using XYAC.Framework.MonitorTireMaterialManual.Extensions;
using XYAC.Framework.MonitorTireMaterialManual.IServices;
using XYAC.Framework.MonitorTireMaterialManual.LocalData.Models;
using XYAC.Framework.MonitorTireMaterialManual.OracleRemoteDB;
using System.Timers;
using System.Diagnostics;
using System.Windows;
using XYAC.Framework.MonitorTireMaterialManual.Views;
using System.Collections.ObjectModel;
using System.Numerics;
using System.Windows.Media;
using System.Windows.Threading;

namespace XYAC.Framework.MonitorTireMaterialManual.ViewModels
{
    public partial class QualityDataUploadViewModel : ViewModelBase
    {
        public QualityDataUploadViewModel(IOptionsMonitor<AppConfig> appConfig, 
            ILogger<QualityDataUploadViewModel> logger, IServiceProvider provider)
        {
            this.AppConfig = appConfig;
            this.Logger = logger;
            this.Provider = provider;
            UploadingColor = Brushes.LightBlue;
            this.IsUseCustomizePlanDate = this.AppConfig.CurrentValue.IsUseCustomizePlanDate;
            this.CustomizePlanDate = this.AppConfig.CurrentValue.CustomizePlanDate;
            InitializeTask();
            RefershInspectData();
            RefershHistoryData();
        }

        /// <summary>
        /// 初始化数据刷新定时器
        /// </summary>
        private void InitializeTask()
        {
            _machineTypeList = new ObservableCollection<Item>();

            MachineTypeList.Add(new Item
            {
                Caption = "胎面",
                Value = "1"
            });
            MachineTypeList.Add(new Item
            {
                Caption = "胎侧",
                Value = "2"
            });
            MachineTypeList.Add(new Item
            {
                Caption = "三角胶",
                Value = "3"
            });

            var Timer = new System.Timers.Timer();
            Timer.Interval = 1 * 30 * 1000;
            Timer.Elapsed += Timer_Elapsed;
            Timer.Start();
            Timer_Elapsed(null, null);

            var DateUpdateTimer = new System.Timers.Timer();
            DateUpdateTimer.Interval = 3 * 1000;
            DateUpdateTimer.Elapsed += DateUpdateTimer_Elapsed;
            DateUpdateTimer.Start();
            DateUpdateTimer_Elapsed(null, null);

        }

        private void DateUpdateTimer_Elapsed(object? sender, ElapsedEventArgs e)
        {
            this.MinProduceDate = DateTime.Now.Date.AddDays(-1);
            this.MaxProduceDate = DateTime.Now.Date.AddDays(1);

        }

        private void Timer_Elapsed(object? sender, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                //刷新计划数据
                RefershInspectData();
                //刷新历史记录数据
                RefershHistoryData();
            }
            catch (Exception)
            {

            }
        }
        [ObservableProperty]
        private Brush _uploadingColor;

        [RelayCommand]
        private async void ManuUploadData()
        {
            await Task.Run(() =>
            {
                ILocalDataService service = null!;
                try
                {
                    service = Provider.GetService<ILocalDataService>();
                    var ret = 0;
                    UploadingColor = Brushes.GreenYellow;
                    try
                    {
                        ret = service.SyncSemiSteelTreadScanReport_SpecDt_ToRemote(CustomizePlanDate.GetValueOrDefault(DateTime.Now));
                    }
                    catch (Exception)
                    {

                    }
                    try
                    {
                        ret = service.SyncSemiSteelSideInspectionReport_SpecDt_ToRemote(CustomizePlanDate.GetValueOrDefault(DateTime.Now));
                    }
                    catch (Exception)
                    {
                    }
                    try
                    {
                        ret = service.SyncSemiSteelTriangleRubberReport_SpecDt_ToRemote(CustomizePlanDate.GetValueOrDefault(DateTime.Now));
                    }
                    catch (Exception)
                    {
                    }
                }
                catch (Exception)
                {
                    this.Logger?.LogError("");
                }
                finally
                {
                    UploadingColor = Brushes.LightBlue;
                }
            });
        }

        [RelayCommand]
        private void PreCheck()
        {
            var view = this.Provider.GetService<PreCheckView2>();
            view?.setMode(false);
            var Window = new Window();
            Window.Title = "标准块检测";
            Window.Content = view;
            Window.Width = 800;
            Window.Height = 700;
            Window.ResizeMode = ResizeMode.NoResize;
            Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            var result = Window.ShowDialog();
            if (result == true)
            {
                this.RefershInspectData();
                this.CurrentUserChoicePlan = null!;
            }
        }

        /// <summary>
        /// 选择计划
        /// </summary>
        /// <param name="plan"></param>
        /// <returns></returns>
        [RelayCommand]
        private void ChoicePlan(YB_LOT_INSPECTViewModel? plan)
        {
            try
            {
                if (plan is not null)
                {
                    if (this.CurrentUserChoicePlan is not null)
                        this.CurrentUserChoicePlan.LocalSyncState = 0;
                    Debug.WriteLine($"ChoicePlan:用户选择条码:{plan.InspectModel.SERIAL_NUMBER}");
                     
                    this.CurrentUserChoicePlan = plan;
                    this.CurrentUserChoicePlan.LocalSyncState = -1;
                    //SelectedDetectionMachine.EqpNo.Contains("GB")
                    if (this.SelectedDetectionMachine.EqpType == __EQPTYPE__TYPE1)
                    {
                        var view = this.Provider.GetService<SemiSteelTreadScanView2>();
                        view.ClearViewModelValue();
                        view.setMode(false);
                        view.setCurrentInspect(plan);
                        var Window = new Window();
                        Window.Title = this.SelectedDetectionMachine.EqpName;
                        Window.Content = view;
                        //Window.WindowState = WindowState.Maximized;
                        Window.Width = 800;
                        Window.Height = 820;
                        Window.ResizeMode = ResizeMode.NoResize;
                        Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        var result = Window.ShowDialog();
                        if (result == true)
                        {
                            this.RefershInspectData();
                            this.CurrentUserChoicePlan = null;
                        }
                        //var report = view.ViewModel.SemiSteelTreadScanReport;

                    }
                    else if (this.SelectedDetectionMachine.EqpType == __EQPTYPE__TYPE2)
                    {
                        var view = this.Provider.GetService<SemiSteelSideInspectionView2>();
                        view.ClearViewModelValue();
                        view.setMode(false);
                        //view.setCurrentInspect(plan);
                        var Window = new Window();
                        Window.Title = this.SelectedDetectionMachine.EqpName;
                        Window.Content = view;
                        //Window.WindowState = WindowState.Maximized;
                        Window.Width = 800;
                        Window.Height = 820;
                        Window.ResizeMode = ResizeMode.NoResize;
                        Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        var result = Window.ShowDialog();
                        if (result == true)
                        {
                            this.RefershInspectData();
                            this.CurrentUserChoicePlan = null;
                        }
                        //var report = view.ViewModel.SemiSteelSideInspectionReport;
                    }
                    else if (this.SelectedDetectionMachine.EqpType == __EQPTYPE__TYPE3)
                    {
                        var view = this.Provider.GetService<SemiSteelTriangleRubberView2>();
                        view.ClearViewModelValue();
                        view.setMode(false);
                        //view.setCurrentInspect(plan);
                        var Window = new Window();
                        Window.Title = this.SelectedDetectionMachine.EqpName;
                        Window.Content = view;
                        //Window.WindowState = WindowState.Maximized;
                        Window.Width = 750;
                        Window.Height = 600;
                        Window.ResizeMode = ResizeMode.NoResize;
                        Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                        var result = Window.ShowDialog();
                        if (result == true)
                        {
                            this.RefershInspectData();
                            this.CurrentUserChoicePlan = null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
        }

        [RelayCommand]
        private void ViewReport(ReportEntityBase report)
        {
            Dispatcher.CurrentDispatcher.Invoke(() =>
            {

                if (report is SemiSteelSideInspectionReport vm)
                {
                    //var view = this.provider.GetService<SemiSteelSideInspectionReadonlyView>();
                    var view = this.Provider.GetService<SemiSteelSideInspectionView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.SemiSteelSideInspectionReport = vm;
                    var Window = new Window();
                    Window.Title = "胎侧检测结果查看";
                    Window.Content = view;
                    Window.Width = 800;
                    Window.Height = 820;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //Window.WindowState = WindowState.Maximized;
                    var result = Window.ShowDialog();
                }
                else if (report is SemiSteelTriangleRubberReport vm1)
                {
                    //var view = this.provider.GetService<SemiSteelTriangleRubberReadonlyView>();
                    //var view = this.provider.GetService<SemiSteelTriangleRubberView1>();
                    var view = this.Provider.GetService<SemiSteelTriangleRubberView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.SemiSteelTriangleRubberReport = vm1;
                    var Window = new Window();
                    Window.Title = "三角胶检测结果查看";
                    Window.Content = view;
                    Window.Width = 750;
                    Window.Height = 600;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //Window.WindowState = WindowState.Maximized;
                    var result = Window.ShowDialog();
                }
                else if (report is SemiSteelTreadScanReport vm2)
                {
                    //var view = this.provider.GetService<SemiSteelTreadScanReadonlyView>();
                    var view = this.Provider.GetService<SemiSteelTreadScanView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.SemiSteelTreadScanReport = vm2;
                    var Window = new Window();
                    Window.Title = "胎面检测结果查看";
                    Window.Content = view;
                    Window.Width = 800;
                    Window.Height = 820;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    //Window.WindowState = WindowState.Maximized;
                    var result = Window.ShowDialog();
                }
                else if (report is PreCheckReport vm3)
                {
                    //var view = this.provider.GetService<SemiSteelTreadScanReadonlyView>();
                    var view = this.Provider.GetService<PreCheckView2>();
                    view.ClearViewModelValue();
                    view.setMode(true);
                    view.ViewModel.PreCheckReport = vm3;
                    var Window = new Window();
                    Window.Title = "标准块检测结果查看";
                    Window.Content = view;
                    Window.Width = 800;
                    Window.Height = 700;
                    Window.ResizeMode = ResizeMode.NoResize;
                    Window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                    var result = Window.ShowDialog();
                }
            });
        }


        /// <summary>
        /// 标签选择变更事件
        /// </summary>
        [RelayCommand]
        private void TabSelectionChanged(int selectedIndex)
        {

            RefershInspectData();

        }
        /// <summary>
        /// 刷新历史记录数据
        /// </summary>
        private void RefershHistoryData()
        {
            try
            {
                var planDate = CurrentProduceDate;
                if (this.AppConfig.CurrentValue.IsUseCustomizePlanDate == true && this.AppConfig.CurrentValue.CustomizePlanDate.HasValue)
                {
                    planDate = this.AppConfig.CurrentValue.CustomizePlanDate.Value;
                }
                using (var scope = this.Provider.CreateScope())
                {
                    if (this.SelectedHistoryType == 0)
                    {
                        this.SemiSteelTreadScanReports = RefershLocalRecordsDetails<SemiSteelTreadScanReport>(planDate);
                    }
                    else if (this.SelectedHistoryType == 1)
                    {
                        this.SemiSteelSideInspectionReports = RefershLocalRecordsDetails<SemiSteelSideInspectionReport>(planDate);

                    }
                    else if (this.SelectedHistoryType == 2)
                    {
                        this.SemiSteelTriangleRubberReports = RefershLocalRecordsDetails<SemiSteelTriangleRubberReport>(planDate);
                    }
                    else if (this.SelectedHistoryType == 3)//标准块
                    {
                        this.PreCheckReports = RefershLocalRecordsDetails<PreCheckReport>(planDate);
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        [RelayCommand]
        private void HistorySelectionChanged(int selectedType)
        {
            if (selectedType != this.HistorySelectedIndex)
            {
                this.HistorySelectedIndex = selectedType;
                RefershHistoryData();
            }
        }


        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        private IEnumerable<TType> RefershLocalRecordsDetails<TType>(DateTime planDate, int pageIndex = 0, int pageSize = 20) where TType : ReportEntityBase, new()
        {
            try
            {
                using (var scope = this.Provider.CreateScope())
                {
                    var service = scope.ServiceProvider.GetService<ILocalReportService>();
                    var data = service.GetPage<TType>(pageIndex, pageSize,
                        filterConditions: new()
                        {
                            T=>T.PlanDate.Date==planDate.Date
                        },
                        orderConditions: new()
                        {
                          new(T=>T.ID,true)//使用ID逆序排序
                        });

                    return data;
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
                return Enumerable.Empty<TType>();
            }
        }
        /// <summary>
        /// 刷新计划数据
        /// </summary>
        public void RefershInspectData()
        {
            try
            {
                using (var scope = this.Provider.CreateScope())
                {
                    var eqp = this.SelectedDetectionMachine?.EqpNo;
                    var service = scope.ServiceProvider.GetService<ILocalDataService>();

                    if (eqp == null)
                    {
                        eqp = service.GetAll<Entities.EquipmentMapping>().FirstOrDefault()?.EqpNo;
                    }
                    if (!this.AppConfig.CurrentValue.IsUseCustomizePlanDate)
                    {

                        this.CurrentMachinePlanList = service.GetPage<YB_LOT_INSPECT_Local>(0, 40, new()
                        {
                            T=>T.RemoteSyncState==false,//远程同步状态为未传送
                            T=>T.EQP==eqp,
                            T=>T.PLAN_DATE==this.CurrentProduceDate,
                            T=>T.SHIFT==this.AppConfig.CurrentValue.GetCurrentShift()
                        }).Select(T => new YB_LOT_INSPECTViewModel(T));
                    }
                    else
                    {
                        this.CurrentMachinePlanList = service.GetPage<YB_LOT_INSPECT_Local>(0, 40, new()
                        {
                            T=>T.RemoteSyncState==false,//远程同步状态为未传送
                            T=>T.EQP==eqp,
                            T=>T.PLAN_DATE==this.CurrentProduceDate,
                        }).Select(T => new YB_LOT_INSPECTViewModel(T));
                    }
                }
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 修改自定义计划时间
        /// </summary>
        [RelayCommand]
        private void ChangeIsUseCustomizePlanDate()
        {
            try
            {
                this.AppConfig.CurrentValue.IsUseCustomizePlanDate = this.IsUseCustomizePlanDate;

                SaveNewJsonConfig();
                RefershInspectData();
                //SaveNewXmlConfig();
            }
            catch (Exception ex)
            {
                this.Logger.LogError("保存使用计划配置节点失败", ex);
            }
        }
        private void SaveNewJsonConfig()
        {
            try
            {
                const string configPath = "./Configs/";
                const string configFileName = "AppConfig.json";
                const string tempFileName = "AppConfig_temp.json";

                string configFullPath = Path.Combine(configPath, configFileName);
                string tempFullPath = Path.Combine(configPath, tempFileName);

                // 复制原始配置文件到临时文件
                File.Copy(configFullPath, tempFullPath, overwrite: true);
                var currentValue = this.AppConfig.CurrentValue.Clone();
                // 修改临时文件
                JsonObject appSetting;
                using (FileStream fs = new FileStream(tempFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
                {
                    appSetting = JsonNode.Parse(fs).AsObject();

                    // 将当前的 CurrentAppConfig 序列化为 JsonNode
                    JsonNode sourceJsonNode = JsonSerializer.SerializeToNode(currentValue);

                    // 替换 "AppConfig" 节点
                    appSetting["AppConfig"] = sourceJsonNode;

                    // 清空文件并重置位置
                    fs.SetLength(0);
                    fs.Position = 0;

                    var options = new JsonSerializerOptions
                    {
                        WriteIndented = true // 格式化输出
                    };
                    JsonSerializer.Serialize(fs, appSetting, options);
                }

                // 原子性地替换原始配置文件
                File.Replace(tempFullPath, configFullPath, null);
            }
            catch (Exception ex)
            {
                this.Logger.LogError("保存配置文件失败", ex);
            }
        }

        /// <summary>
        /// 更新配置计划日期
        /// </summary>
        internal void UpdateCustomizePlanDateWithConfig(DateTimeOffset? newDate)
        {
            try
            {
                if (newDate.HasValue)
                    this.AppConfig.CurrentValue.CustomizePlanDate = newDate.Value.DateTime;

                SaveNewJsonConfig();

                this.RefershInspectData();
                //SaveNewXmlConfig();
            }
            catch (Exception ex)
            {
                this.Logger.LogError("保存配置计划日期失败", ex);
            }
        }

        public void SelectPlatformByType(string mType)
        {
            using (var scope = Provider.CreateScope())
            {
                try
                {
                    var context = scope.ServiceProvider.GetService<ILocalDataService>();
                    var result = context.GetAll<Entities.EquipmentMapping>();
                    
                    this.CurrentMachineList = result.Where(x=>x.EqpType==mType).OrderBy(x=>x.ID).ToList();
                }
                catch (Exception)
                {
                    MessageBox.Show("查询所有设备映射失败，请检查数据库连接是否正常");
                }

            }
        }

        #region Properties
        /// <summary>
        /// 配置的检测机台
        /// </summary>
        [ObservableProperty]
        private IEnumerable<Entities.EquipmentMapping> _detectionMachineList;

        //[ObservableProperty]
        public IEnumerable<Entities.EquipmentMapping> CurrentMachineList
        {
            get { return _detectionMachineList; }
            set { SetProperty(ref _detectionMachineList, value); }
        }
        
        /// <summary>
        /// 系统配置
        /// </summary>
        private IOptionsMonitor<AppConfig> AppConfig;

        /// <summary>
        /// 当前选择标签计划集合
        /// </summary>
        [ObservableProperty]
        private IEnumerable<YB_LOT_INSPECTViewModel> _currentMachinePlanList;
        public ILogger<QualityDataUploadViewModel> Logger { get; }
        public IServiceProvider Provider { get; }
        /// <summary>
        /// 三角胶历史记录
        /// </summary>
        [ObservableProperty]
        public IEnumerable<SemiSteelTriangleRubberReport> _semiSteelTriangleRubberReports;
        /// <summary>
        /// 胎侧历史记录
        /// </summary>
        [ObservableProperty]
        public IEnumerable<SemiSteelSideInspectionReport> _semiSteelSideInspectionReports;
        /// <summary>
        /// 胎面历史记录
        /// </summary>
        [ObservableProperty]
        public IEnumerable<SemiSteelTreadScanReport> _semiSteelTreadScanReports;
        /// <summary>
        /// 标准历史记录
        /// </summary>
        [ObservableProperty]
        public IEnumerable<PreCheckReport> _preCheckReports;

        /// <summary>
        /// 用户选择计划
        /// </summary>
        [ObservableProperty]
        private YB_LOT_INSPECTViewModel _currentUserChoicePlan;

        /// <summary>
        /// 选择检测过的数据类型：如胎面类型、胎侧类型、三角胶类型等
        /// </summary>

        [ObservableProperty]
        private int? _selectedHistoryType = 0;

        /// <summary>
        /// 当前选择计划日期开关
        /// </summary>
        [ObservableProperty]
        private bool _isUseCustomizePlanDate;

        [ObservableProperty]
        public Item _currentSelection;
        /// <summary>
        /// 最小选择的日期
        /// </summary>
        [ObservableProperty]
        private DateTime minProduceDate = DateTime.Now.Date.AddDays(-1);
        /// <summary>
        /// 最小选择的日期
        /// </summary>
        [ObservableProperty]
        private DateTime maxProduceDate = DateTime.Now.Date.AddDays(1);
        /// <summary>
        /// 当前计划生产时间
        /// </summary> 
        private DateTime CurrentProduceDate { get => this.AppConfig.CurrentValue.GetCurrentProcuceDate(); }
        public int HistorySelectedIndex { get; private set; }

        /// <summary>
        /// 当前选择机台
        /// </summary>
        [ObservableProperty]
        private Entities.EquipmentMapping _selectedDetectionMachine;

        [ObservableProperty]
        private ObservableCollection<Item> _machineTypeList;
        

        /// <summary>
        /// 自定义日期
        /// </summary>
        [ObservableProperty]
        private DateTime? _customizePlanDate;

        private const string __EQPTYPE__TYPE1 = "1";
        private const string __EQPTYPE__TYPE2 = "2";
        private const string __EQPTYPE__TYPE3 = "3";
        private const string __EQPTYPE__TYPE4 = "4";//班前检点

        #endregion
    }

    /// <summary>
    /// 名值对。
    /// 用于Combobox 下拉等。
    /// </summary>
    public class Item
    {
        public string Caption { get; set; }
        public string Value { get; set; }
        public Item() { }
        public Item(string caption, string value)
        {
            Caption = caption;
            Value = value;
        }
        public override string ToString()
        {
            return Caption;
        }
    }
}
